"use client";

import { useState, useEffect } from "react";
import { PlayCircle, PauseCircle, SkipBack, SkipForward, Heart, Search, Music, Volume2 } from "lucide-react";
import { VmsMusic } from "@/types/Model";

export default function MusicPlayer() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentMusic, setCurrentMusic] = useState<VmsMusic>({
    id: "",
    title: "",
    audio_url: "",
    music_type: ""
  });
  const [musicList, setMusicList] = useState<VmsMusic[]>([]);
  const [selectedCategory, setSelectedCategory] = useState("科技数码");
  const categories = [
    "科技数码",
    "知识教程", 
    "美食手工",
    "旅行探险",
    "游戏解说",
    "Vlog",
    "纪录片",
    "微电影",
    "宣传片",
  ];

  useEffect(() => {
    const fetchMusic = async () => {
      try {
        const response = await fetch('/api/music');
        const data = await response.json();
        const sortedData = data.sort((a: VmsMusic, b: VmsMusic) => (b.score || 0) - (a.score || 0));
        setMusicList(sortedData);
        if (sortedData.length > 0) {
          setCurrentMusic(sortedData[0]);
        }
      } catch (error) {
        console.error('Failed to fetch music:', error);
      }
    };

    fetchMusic();
  }, []);

  const handleLike = async (musicId: string) => {
    try {
      const response = await fetch(`/api/music/like/${musicId}`, {
        method: 'POST'
      });
      const updatedMusic = await response.json();
      
      setMusicList(prev => 
        prev.map(music => 
          music.id === updatedMusic.id 
            ? {...music, score: updatedMusic.score} 
            : music
        )
      );
      
      if (currentMusic.id === updatedMusic.id) {
        setCurrentMusic(updatedMusic);
      }
    } catch (error) {
      console.error('Failed to like music:', error);
    }
  };

  const playMusic = (item: VmsMusic) => {
    setCurrentMusic(item);
    setIsPlaying(true);
    const audio = document.getElementById("myAudio") as HTMLAudioElement;
    audio.src = item.audio_url || '';
    audio.play();
  };

  const pauseMusic = () => {
    setIsPlaying(false);
    const audio = document.getElementById("myAudio") as HTMLAudioElement;
    audio.pause();
  };

  const nextMusic = () => {
    const currentIndex = musicList.findIndex((music) => music.id === currentMusic.id);
    const nextIndex = (currentIndex + 1) % musicList.length;
    playMusic(musicList[nextIndex]);
  };

  const prevMusic = () => {
    const currentIndex = musicList.findIndex((music) => music.id === currentMusic.id);
    const prevIndex = (currentIndex - 1 + musicList.length) % musicList.length;
    playMusic(musicList[prevIndex]);
  };

  const filteredMusicList = musicList.filter(music => {
    const matchesCategory = selectedCategory === "全部" || music.theme === selectedCategory;
    const matchesSearch = music.title?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         music.music_type?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         music.tags?.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesCategory && matchesSearch;
  });

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-rose-50 to-indigo-100">
      {/* 主内容区域 */}
      <div className="pb-32">
        <div className="max-w-6xl mx-auto px-6 py-8">
          {/* 页面标题 */}
          <div className="mb-8">
            <div className="flex items-center gap-3 mb-2">
              <div className="p-2 bg-gradient-to-r from-rose-500 to-purple-600 rounded-xl">
                <Music className="w-6 h-6 text-white" />
              </div>
              <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-gray-600 bg-clip-text text-transparent">
                音乐库
              </h1>
            </div>
            <p className="text-gray-600">发现适合您项目的完美背景音乐</p>
          </div>

          {/* 搜索框 */}
          <div className="relative mb-6">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="search"
              placeholder="搜索音乐标题、类型或标签..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full h-12 pl-12 pr-4 rounded-xl border border-gray-200 bg-white/80 backdrop-blur-sm text-sm placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-transparent shadow-sm transition-all duration-200"
            />
          </div>

          {/* 分类筛选 */}
          <div className="mb-8">
            <h3 className="text-sm font-medium text-gray-700 mb-3">音乐分类</h3>
            <div className="flex flex-wrap gap-2">
              {categories.map(category => (
                <button
                  key={category}
                  onClick={() => setSelectedCategory(category)}
                  className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                    selectedCategory === category
                      ? 'bg-gradient-to-r from-rose-500 to-purple-600 text-white shadow-lg shadow-rose-500/25 scale-105'
                      : 'bg-white/80 backdrop-blur-sm text-gray-700 hover:bg-white hover:shadow-md border border-gray-200'
                  }`}
                >
                  {category}
                </button>
              ))}
            </div>
          </div>

          {/* 统计信息 */}
          <div className="mb-6">
            <div className="flex items-center justify-between">
              <p className="text-sm text-gray-600">
                找到 <span className="font-semibold text-rose-600">{filteredMusicList.length}</span> 首音乐
              </p>
              {searchTerm && (
                <p className="text-sm text-gray-500">
                  搜索: "{searchTerm}"
                </p>
              )}
            </div>
          </div>

          {/* 音乐列表 */}
          <div className="space-y-3">
            {filteredMusicList.length === 0 ? (
              <div className="text-center py-16">
                <Music className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-500 mb-2">暂无音乐</h3>
                <p className="text-gray-400">尝试调整搜索条件或选择其他分类</p>
              </div>
            ) : (
              filteredMusicList.map((item, index) => (
                <div
                  key={item.id}
                  className={`group relative p-4 bg-white/80 backdrop-blur-sm rounded-xl border border-gray-200 hover:bg-white hover:shadow-lg hover:shadow-rose-500/10 cursor-pointer transition-all duration-300 ${
                    item.id === currentMusic.id ? 'ring-2 ring-rose-500 bg-rose-50/50' : ''
                  }`}
                  onClick={() => playMusic(item)}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-4 flex-1 min-w-0">
                      {/* 播放按钮 */}
                      <div className="relative">
                        {item.id === currentMusic.id && isPlaying ? (
                          <div className="relative">
                            <PauseCircle className="w-12 h-12 text-rose-600" />
                            <div className="absolute inset-0 rounded-full bg-rose-500/20 animate-pulse" />
                          </div>
                        ) : (
                          <PlayCircle className="w-12 h-12 text-gray-600 group-hover:text-rose-600 transition-colors duration-200" />
                        )}
                      </div>
                      
                      {/* 音乐信息 */}
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-base font-semibold text-gray-900 truncate">
                            {item.title}
                          </span>
                          {item.id === currentMusic.id && (
                            <div className="flex items-center gap-1">
                              <Volume2 className="w-4 h-4 text-rose-600" />
                              <span className="text-xs text-rose-600 font-medium">正在播放</span>
                            </div>
                          )}
                        </div>
                        <div className="flex items-center gap-2 flex-wrap">
                          {item.music_type && (
                            <span className="text-xs text-rose-700 bg-rose-100 px-2 py-1 rounded-full font-medium">
                              {item.music_type}
                            </span>
                          )}
                          {item.tags && (
                            <span className="text-xs text-purple-700 bg-purple-100 px-2 py-1 rounded-full font-medium">
                              {item.tags}
                            </span>
                          )}
                          <span className="text-xs text-gray-600 flex items-center gap-1">
                            <Heart className="w-3 h-3 fill-red-500 text-red-500" />
                            <span className="font-medium">{item.score || 0}</span>
                          </span>
                        </div>
                      </div>
                    </div>
                    
                    {/* 点赞按钮 */}
                    <button 
                      onClick={(e) => {
                        e.stopPropagation();
                        handleLike(item.id);
                      }}
                      className="p-2 hover:bg-red-50 rounded-full transition-colors duration-200 group/like"
                    >
                      <Heart className="w-5 h-5 text-gray-400 group-hover/like:text-red-500 group-hover/like:fill-red-500 transition-all duration-200" />
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>

      {/* 播放控制栏 */}
      <div className="fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-md border-t border-gray-200 shadow-2xl">
        <div className="max-w-6xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            {/* 控制按钮 */}
            <div className="flex items-center space-x-2">
              <button 
                onClick={prevMusic} 
                className="p-3 hover:bg-gray-100 rounded-full transition-colors duration-200"
              >
                <SkipBack className="w-5 h-5 text-gray-600" />
              </button>
              <button
                onClick={isPlaying ? pauseMusic : () => playMusic(currentMusic)}
                className="p-3 bg-gradient-to-r from-rose-500 to-purple-600 hover:from-rose-600 hover:to-purple-700 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl"
              >
                {isPlaying ? (
                  <PauseCircle className="w-6 h-6 text-white" />
                ) : (
                  <PlayCircle className="w-6 h-6 text-white" />
                )}
              </button>
              <button 
                onClick={nextMusic} 
                className="p-3 hover:bg-gray-100 rounded-full transition-colors duration-200"
              >
                <SkipForward className="w-5 h-5 text-gray-600" />
              </button>
            </div>
            
            {/* 当前播放信息 */}
            <div className="flex-1 text-center mx-8">
              <p className="text-lg font-bold text-gray-900 truncate">
                {currentMusic.title || "请选择音乐"}
              </p>
              <p className="text-sm text-gray-500">
                {currentMusic.music_type || "暂无播放"}
              </p>
            </div>
            
            {/* 音频控件 */}
            <div className="flex items-center">
              <audio 
                id="myAudio" 
                className="w-64 h-8" 
                controls
                style={{
                  filter: 'sepia(20%) saturate(70%) hue-rotate(200deg) brightness(1.2)'
                }}
              >
                <source src={currentMusic.audio_url || ''} type="audio/mpeg" />
              </audio>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}